<template>
  <view class="seckill-item" @click="onClick">
    <!-- 商品图片区域 -->
    <view class="image-section">
      <image 
        :src="item.dishImg || item.dishImage || item.imgUrl || '/static/default-product.jpg'" 
        class="product-image" 
        mode="aspectFill" 
      />
      <view :class="['status-badge', statusClass]">
        {{ statusText }}
      </view>
      <view v-if="discountPercent" class="discount-badge">
        {{ discountPercent }}折
      </view>
    </view>

    <!-- 商品信息区域 -->
    <view class="info-section">
      <!-- 商品名称 -->
      <text class="plan-name">{{ item.dishName || item.planName || `商品${item.dishId}` }}</text>
      
      <!-- 价格区域 -->
      <view class="price-section">
        <view class="price-row">
          <text class="seckill-price">¥{{ item.seckillPrice }}</text>
          <text class="original-price">¥{{ originalPrice }}</text>
        </view>
        <text class="save-money">省¥{{ savedAmount }}</text>
      </view>

      <!-- 进度条 -->
      <view class="progress-section">
        <view class="progress-info">
          <text class="progress-label">已抢{{ soldPercent }}%</text>
          <text class="stock-info">剩余{{ remainingStock }}件</text>
        </view>
        <view class="progress-bar">
          <view class="progress-fill" :style="{ width: progressWidth }"></view>
        </view>
      </view>

      <!-- 底部操作区 -->
      <view class="action-section">
        <!-- 未开始 - 显示倒计时 -->
        <view v-if="currentStatus === 'upcoming'" class="countdown-section">  
          <text class="countdown-label">距开始:</text>
          <view class="countdown-time">
            <text class="time-item">{{ timeLeft.hours }}时</text>
            <text class="time-item">{{ timeLeft.minutes }}分</text>
            <text class="time-item">{{ timeLeft.seconds }}秒</text>
          </view>
        </view>

        <!-- 进行中 - 显示购买按钮 -->
        <button 
          v-else-if="currentStatus === 'active'" 
          class="buy-btn"
          @click.stop="onBuy"
        >
          <text class="btn-text">立即抢购</text>
        </button>

        <!-- 已结束 -->
        <button v-else class="ended-btn" disabled>
          <text class="btn-text">已结束</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, reactive, onMounted, onUnmounted } from 'vue'
import { parseDate, getTimeStatus, getCountdown } from '@/utils/dateUtils'

const props = defineProps({
  item: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['click', 'buy'])

// 倒计时状态
const timeLeft = reactive({
  hours: '00',
  minutes: '00', 
  seconds: '00'
})

let countdownTimer = null

// 计算当前状态
const currentStatus = computed(() => {
  return getTimeStatus(props.item.startTime, props.item.endTime)
})

// 状态文本
const statusText = computed(() => {
  const statusMap = {
    upcoming: '即将开始',
    active: '限时秒杀',
    ended: '已结束'
  }
  return statusMap[currentStatus.value]
})

// 状态样式
const statusClass = computed(() => {
  return {
    upcoming: 'status-upcoming',
    active: 'status-active', 
    ended: 'status-ended'
  }[currentStatus.value]
})

// 计算原价（优先使用从菜品服务获取的原价）
const originalPrice = computed(() => {
  return props.item.originalPrice || props.item.price || (props.item.seckillPrice * 1.5).toFixed(2)
})

// 计算折扣
const discountPercent = computed(() => {
  const original = parseFloat(originalPrice.value)
  const seckill = props.item.seckillPrice || 0
  if (original && seckill && original > seckill) {
    return Math.floor((seckill / original) * 10)
  }
  return null
})

// 计算节省金额
const savedAmount = computed(() => {
  const original = parseFloat(originalPrice.value)
  const seckill = props.item.seckillPrice || 0
  return (original - seckill).toFixed(2)
})

// 计算剩余库存
const remainingStock = computed(() => {
  return props.item.seckillQuantity || props.item.stock || 0
})

// 进度计算
const soldPercent = computed(() => {
  // 获取原始总库存（从数据库）
  const originalTotal = props.item.originalSeckillQuantity || props.item.seckillQuantity || props.item.limitBuy || props.item.stock || 100
  // 获取当前剩余库存（实时更新的）
  const remaining = remainingStock.value
  // 计算已售数量
  const sold = originalTotal - remaining
  
  console.log('进度计算:', {
    originalTotal,
    remaining,
    sold,
    percent: Math.max(0, Math.floor((sold / originalTotal) * 100))
  })
  
  return Math.max(0, Math.floor((sold / originalTotal) * 100))
})

const progressWidth = computed(() => {
  return `${Math.min(soldPercent.value, 100)}%`
})

onMounted(() => {
  if (currentStatus.value === 'upcoming') {
    startCountdown()
  }
})

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})

// 开始倒计时
function startCountdown() {
  updateCountdown()
  countdownTimer = setInterval(updateCountdown, 1000)
}

// 更新倒计时
function updateCountdown() {
  const countdown = getCountdown(props.item.startTime)
  
  if (countdown.totalSeconds <= 0) {
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
    return
  }
  
  timeLeft.hours = countdown.hours
  timeLeft.minutes = countdown.minutes
  timeLeft.seconds = countdown.seconds
}

// 点击事件
function onClick() {
  emit('click', props.item)
}

// 购买事件
function onBuy() {
  emit('buy', props.item)
}
</script>

<style scoped>
.seckill-item {
  background: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
}

.seckill-item:active {
  transform: scale(0.98);
}

/* 图片区域 */
.image-section {
  position: relative;
  height: 300rpx;
}

.product-image {
  width: 100%;
  height: 100%;
}

.status-badge {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: bold;
  color: #ffffff;
}

.status-upcoming {
  background: linear-gradient(135deg, #ff9500 0%, #ff6b00 100%);
}

.status-active {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  animation: pulse 2s infinite;
}

.status-ended {
  background: #999999;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}

.discount-badge {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  color: #ffffff;
  padding: 8rpx 12rpx;
  border-radius: 16rpx;
  font-size: 20rpx;
  font-weight: bold;
}

/* 信息区域 */
.info-section {
  padding: 30rpx;
}

.plan-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #1a1a1a;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 价格区域 */
.price-section {
  margin-bottom: 20rpx;
}

.price-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 8rpx;
}

.seckill-price {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff4757;
  margin-right: 16rpx;
}

.original-price {
  font-size: 26rpx;
  color: #999999;
  text-decoration: line-through;
}

.save-money {
  font-size: 24rpx;
  color: #ff4757;
  background: rgba(255, 71, 87, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

/* 进度区域 */
.progress-section {
  margin-bottom: 24rpx;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.progress-label {
  font-size: 24rpx;
  color: #ff4757;
  font-weight: 600;
}

.stock-info {
  font-size: 24rpx;
  color: #666666;
}

.progress-bar {
  height: 12rpx;
  background: #f5f5f5;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #ff6b6b 0%, #ff4757 100%);
  border-radius: 6rpx;
  transition: width 0.3s ease;
}

/* 操作区域 */
.action-section {
  height: 80rpx;
  display: flex;
  align-items: center;
}

.countdown-section {
  display: flex;
  align-items: center;
  width: 100%;
}

.countdown-label {
  font-size: 26rpx;
  color: #666666;
  margin-right: 16rpx;
}

.countdown-time {
  display: flex;
  align-items: center;
}

.time-item {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  font-size: 22rpx;
  font-weight: bold;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  margin-right: 8rpx;
}

.buy-btn {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
  border: none;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(255, 71, 87, 0.4);
}

.ended-btn {
  width: 100%;
  height: 100%;
  background: #cccccc;
  border: none;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #ffffff;
}
</style> 